function sprintf() {
    var arg = arguments,
            str = arg[0] || '',
            i, n;
    for (i = 1, n = arg.length; i < n; i++) {
        str = str.replace(/%s/, arg[i]);
    }
    return str;
}

function loadRegion(sel,type_id,selName,url, selected){
    selected = selected ? selected : false;
	$("#"+selName+" option").each(function(){
		$(this).remove();
	});
    $("#"+selName).next().find("option").each(function(){
		$(this).remove();
	});
	if($("#"+sel).val()==0){
		return;
	}
	$.getJSON(url,{pid:$("#"+sel).val(),type:type_id},
		function(data){
            var theselected;
            var selectedId;
			if(data){
				$.each(data,function(idx,item){
                    if(selected == item.id) {
                        theselected = " selected";
                        selectedId = item.id;
                    } else {
                        theselected = "";
                        selectedId = 0;
                    }
					$("<option value="+item.id+theselected+">"+item.name+"</option>").appendTo($("#"+selName));
				});
			}else{
				$("<option value='0'>请选择</option>").appendTo($("#"+selName));
                selectedId = 0;
			}
            
            $("#"+selName).select2("val", selectedId);
		}
	);
}


$(function() {
    if ($(".RelationshipCompanySelect").length > 0) {
        RelCompany.BindEvent();
    }

    
    //默认选择地区
    if($("#province").length > 0) {
        if(parseInt($("#province").attr("cityid")) > 0) {
            loadRegion("province","2","city",_APP_+"/HOME/Region/ajax_getRegion", $("#province").attr("cityid"));
            var t = setInterval(function(){
                loadRegion("city","3","town",_APP_+"/HOME/Region/ajax_getRegion", $("#province").attr("townid"));
            }, 500);
        }
    }
    
    if($("#selectCustomerBtn").length > 0) {
        $(document).delegate("#selectCustomerBtn", "click", function(){
            RelCompany.getCompanyDataTable();
        });
    }
    
    if($(".data-table").length > 0) {
        $(".data-table").dataTable({
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "sDom": '<""l>t<"F"fp>',
            "bSort": false
        });
    }
    
});

Array.prototype.in_array = function(e)
{
    for (i = 0; i < this.length; i++)
    {
        if (this[i] == e)
            return true;
    }
    return false;
}
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val)
            return i;
    }
    return -1;
};
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

var ajaxUpload = function(input_id) {
    $.ajaxFileUpload({
        url: _APP_ + "/HOME/Index/ajax_Upload",
        secureuri: false,
        fileElementId: 'ajax_upload',
        dataType: 'json',
        success: function(data, status) {
            
            if(parseInt(data.error) > 0) {
                alert(data.msg);
            } else {
                $(input_id).val(data.msg);
            }
        }, error: function(data, status) {
            alert(data.msg);
        }
    });
    return false;
}


var Public = {
    tips : function(options) {
        var classes = ['success', 'error', 'info', 'warning'];
        var tpl = '<div class="alert alert-%s" style="display:none;"><button class="close" data-dismiss="alert">×</button>%s</div>';
        var html = sprintf(tpl, classes[options.type], options.content);
        $(".container-fluid").append(html);
        $(".alert").fadeIn(function(){
            setTimeout(function(){
                $(".alert").fadeOut(function(){
                    $(this).find("button").trigger("click");
                });
            }, 2000);
        });
        
    },
    keyCode : {
        ALT: 18,
        BACKSPACE: 8,
        CAPS_LOCK: 20,
        COMMA: 188,
        COMMAND: 91,
        COMMAND_LEFT: 91, // COMMAND
        COMMAND_RIGHT: 93,
        CONTROL: 17,
        DELETE: 46,
        DOWN: 40,
        END: 35,
        ENTER: 13,
        ESCAPE: 27,
        HOME: 36,
        INSERT: 45,
        LEFT: 37,
        MENU: 93, // COMMAND_RIGHT
        NUMPAD_ADD: 107,
        NUMPAD_DECIMAL: 110,
        NUMPAD_DIVIDE: 111,
        NUMPAD_ENTER: 108,
        NUMPAD_MULTIPLY: 106,
        NUMPAD_SUBTRACT: 109,
        PAGE_DOWN: 34,
        PAGE_UP: 33,
        PERIOD: 190,
        RIGHT: 39,
        SHIFT: 16,
        SPACE: 32,
        TAB: 9,
        UP: 38,
        F7: 118,
        F12: 123,
        S: 83,
        WINDOWS: 91 // COMMAND
    },
    bindEnterSkip : function(obj, func){
        var args = arguments;
        $(obj).on('keydown', 'input:visible:not(:disabled)', function(e){
            if (e.keyCode == '13') {
                var inputs = $(obj).find('input:visible:not(:disabled)');
                var idx = inputs.index($(this));
                idx = idx + 1;
                if (idx >= inputs.length) {
                    if (typeof func == 'function') {
                        var _args = Array.prototype.slice.call(args, 2 );
                        func.apply(null,_args);
                    }
                } else {
                    inputs.eq(idx).focus();
                }
            }
        });
    }
}